﻿using System;
using System.Collections.Generic;
using System.Data;
using System.Linq;
using System.Reflection;

namespace DapperORM.Abstractions
{
    /// <summary>
    /// entity database mapper
    /// </summary>
    public interface IEntityTypeMapper
    {
        /// <summary>
        /// 表名映射
        /// </summary>
        string MapTableName();

        /// <summary>
        /// 字段映射
        /// </summary>
        void MapColumn(List<ColumnProperty> columns);
    }

    /// <summary>
    /// entity database mapper
    /// </summary>
    /// <typeparam name="T"></typeparam>
    public interface IEntityTypeMapper<T> : IEntityTypeMapper where T : class
    {
    }

    /// <summary>
    /// DeaultTypeMapper
    /// </summary>
    /// <typeparam name="T"></typeparam>
    public class DeaultEntityTypeMapper<T> : IEntityTypeMapper<T> where T : class
    {
        public virtual string MapTableName()
        {
            var tableName = typeof(T).GetCustomAttribute<TableAttribute>(false)?.Name
                    ?? (typeof(T).GetCustomAttributes(false).FirstOrDefault(attr => attr.GetType().Name == "TableAttribute") as dynamic)?.Name;

            if (tableName == null)
            {
                tableName = typeof(T).Name;
                if (typeof(T).IsInterface && tableName.StartsWith("I"))
                    tableName = tableName.Substring(1);
            }

            return tableName;
        }

        public virtual void MapColumn(List<ColumnProperty> columns)
        {

        }

        public virtual string GetSqlAdapterKey(IDbConnection connection)
        {
            return connection.GetType().Name.ToLower();
        }
    }
}
